import 'dart:convert';

import 'package:flutter/material.dart';
import 'package:flutter_easyloading/flutter_easyloading.dart';
import 'package:flutter_screenutil/flutter_screenutil.dart';
import 'package:provider/provider.dart';
import 'package:taonile/config/config.dart';

import '../entity/user_info_entity.dart';
import '../http/api.dart';
import '../provider/userinfo_provider.dart';
import '../routers/routers.dart';
import '../utils/count_down_time_util.dart';

///
/// 修改绑定手机号
///
class MineChangeMobile extends StatefulWidget {
  MineChangeMobile({Key? key}) : super(key: key);

  @override
  State<MineChangeMobile> createState() => _MineChangeMobileState();
}

class _MineChangeMobileState extends State<MineChangeMobile> {
  String captcha1 = '';
  String codeTips = '获取验证码';
  bool isGetCode = true;

  var captcha2 = "";
  var newMobile = "";
  String codeTips2 = '获取验证码';
  bool isGetCode2 = true;


  int _type = 1;

  late UserInfoEntity infoEntity;

  sendSms(String mobile) async {
    if (mobile.length < 11) {
      return;
    }
    dynamic result = await Api.sendSms({'mobile': mobile});
    var jsonResult = jsonDecode(jsonEncode(result));
    if (jsonResult['code'] == 1) {
      EasyLoading.showToast("验证码已发送，请注意查看短信");
    }
  }

  checkSms(String captcha1) async {
    dynamic result = await Api.checkSms({'mobile': infoEntity.data.mobile, 'captcha': captcha1});
    var jsonResult = jsonDecode(jsonEncode(result));
    if (jsonResult['code'] == 1) {
      setState(() {
        _type = 2;
      });
    }
  }

  changeMobile(String mobile, String captcha) async {
    if (mobile.length < 11) {
      return;
    }
    dynamic result = await Api.changeMobile({'mobile': mobile, 'captcha': captcha});
    var jsonResult = jsonDecode(jsonEncode(result));
    if (jsonResult['code'] == 1) {
      EasyLoading.showToast("手机号码修改成功");
      dynamic users = await Api.getUserinfo();
      Map<String, dynamic> resultUsers = Map.from(users);
      UserInfoEntity infoEntity = UserInfoEntity.fromJson(resultUsers);
      Provider.of<UserInfoProvider>(context, listen: false).changeUserinfo(infoEntity);
      Routes.router.pop(context);
    }
  }

  @override
  Widget build(BuildContext context) {
    infoEntity = Provider.of<UserInfoProvider>(context).userInfo;
    return Scaffold(
      backgroundColor: Config.colorBg2,
      appBar: AppBar(
        title: Text("修改绑定手机"),
        centerTitle: true,
      ),
      body: SizedBox(
        width: double.infinity,
        height: double.infinity,
        child: Stack(
          children: [
            Visibility(
              visible: _type == 1,
              child: Container(
                width: double.infinity,
                height: double.infinity,
                margin: EdgeInsets.symmetric(vertical: 25.w, horizontal: 25.w),
                child: Column(
                  children: [
                    Container(
                      width: double.infinity,
                      padding: EdgeInsets.symmetric(vertical: 20.w, horizontal: 20.w),
                      decoration: BoxDecoration(
                        color: (Config.colorWhite),
                        borderRadius: BorderRadius.circular(10.w),
                      ),
                      child: Column(
                        children: [
                          Row(
                            crossAxisAlignment: CrossAxisAlignment.center,
                            children: [
                              Container(
                                margin: EdgeInsets.symmetric(vertical: 8.w),
                                width: 140.w,
                                child: Text(
                                  "当前手机号",
                                  style: TextStyle(fontSize: 25.sp),
                                ),
                              ),
                              Padding(
                                padding: EdgeInsets.only(left: 30.w),
                              ),
                              Container(
                                width: 480.w,
                                margin: EdgeInsets.symmetric(vertical: 8.w),
                                child: TextField(
                                  keyboardType: TextInputType.text,
                                  textAlign: TextAlign.justify,
                                  obscureText: false,
                                  maxLength: 20,
                                  enabled: false,
                                  maxLines: 1,
                                  onChanged: (value) {
                                    // setState(() {
                                    //   _name = value;
                                    // });
                                  },
                                  style: TextStyle(fontSize: 25.sp, color: Config.colorText1),
                                  decoration: const InputDecoration(
                                    hintStyle: TextStyle(color: Config.colorText3),
                                    hintText: "",
                                    counterText: '',
                                    isDense: true,
                                    border: InputBorder.none,
                                    contentPadding: EdgeInsets.zero, //设置文本内容的Padding
                                  ),
                                  controller: TextEditingController.fromValue(
                                    TextEditingValue(
                                      text: infoEntity.data.mobile,
                                      selection: TextSelection.fromPosition(
                                        TextPosition(
                                            // affinity: TextAffinity.downstream,
                                            offset: infoEntity.data.mobile.length),
                                      ),
                                    ),
                                  ),
                                ),
                              ),
                            ],
                          ),
                          Divider(
                            color: Config.colorDivider,
                            height: 40.w,
                            thickness: 2.w,
                          ),
                          Row(
                            crossAxisAlignment: CrossAxisAlignment.center,
                            children: [
                              Container(
                                margin: EdgeInsets.symmetric(vertical: 8.w),
                                width: 140.w,
                                child: Text(
                                  "验证码",
                                  style: TextStyle(fontSize: 25.sp),
                                ),
                              ),
                              Padding(
                                padding: EdgeInsets.only(left: 30.w),
                              ),
                              Row(
                                children: [
                                  Container(
                                    width: 360.w,
                                    margin: EdgeInsets.symmetric(vertical: 8.w),
                                    child: TextField(
                                      keyboardType: TextInputType.number,
                                      textAlign: TextAlign.justify,
                                      obscureText: false,
                                      maxLength: 6,
                                      maxLines: 1,
                                      onChanged: (value) {
                                        setState(() {
                                          captcha1 = value;
                                        });
                                      },
                                      style: TextStyle(fontSize: 25.sp, color: Config.colorText1),
                                      decoration: const InputDecoration(
                                        hintStyle: TextStyle(color: Config.colorText3),
                                        hintText: "请输入验证码",
                                        counterText: '',
                                        isDense: true,
                                        border: InputBorder.none,
                                        contentPadding: EdgeInsets.zero, //设置文本内容的Padding
                                      ),
                                    ),
                                  ),
                                  InkWell(
                                    onTap: () {
                                      if (!isGetCode) {
                                        return;
                                      }
                                      sendSms(infoEntity.data.mobile);
                                      CountDownTimeUtil(60, 1, (int currentTime) {
                                        var _currentTime = currentTime;
                                        setState(() {
                                          if (_currentTime == 0) {
                                            codeTips = '获取验证码';
                                            isGetCode = true;
                                          } else {
                                            codeTips = '$_currentTime';
                                          }
                                        });
                                      });
                                      isGetCode = false;
                                    },
                                    child: Text(
                                      codeTips,
                                      style: TextStyle(
                                        color: Config.colorMain,
                                        fontSize: 22.sp,
                                      ),
                                    ),
                                  ),
                                ],
                              ),
                            ],
                          ),
                        ],
                      ),
                    ),
                    Container(
                      width: 750.w,
                      height: 96.w,
                      padding: EdgeInsets.symmetric(vertical: 8.w, horizontal: 8.w),
                      margin: EdgeInsets.only(top: 45.w),
                      child: ElevatedButton(
                        clipBehavior: Clip.antiAlias,
                        onPressed: () {
                          setState(() {
                            if (captcha1.length < 6) {
                              EasyLoading.showToast('请输入验证码');
                              return;
                            }
                            checkSms(captcha1);
                          });
                        },
                        style: ElevatedButton.styleFrom(shape: const StadiumBorder()),
                        child: const Text('下一步'),
                      ),
                    ),
                  ],
                ),
              ),
            ),
            Visibility(
              visible: _type == 2,
              child: Container(
                width: double.infinity,
                height: double.infinity,
                margin: EdgeInsets.symmetric(vertical: 25.w, horizontal: 25.w),
                child: Column(
                  children: [
                    Container(
                      width: double.infinity,
                      padding: EdgeInsets.symmetric(vertical: 20.w, horizontal: 20.w),
                      decoration: BoxDecoration(
                        color: (Config.colorWhite),
                        borderRadius: BorderRadius.circular(10.w),
                      ),
                      child: Column(
                        children: [
                          Row(
                            crossAxisAlignment: CrossAxisAlignment.center,
                            children: [
                              Container(
                                margin: EdgeInsets.symmetric(vertical: 8.w),
                                width: 140.w,
                                child: Text(
                                  "新手机号",
                                  style: TextStyle(fontSize: 25.sp),
                                ),
                              ),
                              Padding(
                                padding: EdgeInsets.only(left: 30.w),
                              ),
                              Container(
                                width: 480.w,
                                margin: EdgeInsets.symmetric(vertical: 8.w),
                                child: TextField(
                                  keyboardType: TextInputType.number,
                                  textAlign: TextAlign.justify,
                                  obscureText: false,
                                  maxLength: 11,
                                  maxLines: 1,
                                  onChanged: (value) {
                                    setState(() {
                                      newMobile = value;
                                    });
                                  },
                                  style: TextStyle(fontSize: 25.sp, color: Config.colorText1),
                                  decoration: const InputDecoration(
                                    hintStyle: TextStyle(color: Config.colorText3),
                                    hintText: "请输入新手机号",
                                    counterText: '',
                                    isDense: true,
                                    border: InputBorder.none,
                                    contentPadding: EdgeInsets.zero, //设置文本内容的Padding
                                  ),
                                ),
                              ),
                            ],
                          ),
                          Divider(
                            color: Config.colorDivider,
                            height: 40.w,
                            thickness: 2.w,
                          ),
                          Row(
                            crossAxisAlignment: CrossAxisAlignment.center,
                            children: [
                              Container(
                                margin: EdgeInsets.symmetric(vertical: 8.w),
                                width: 140.w,
                                child: Text(
                                  "验证码",
                                  style: TextStyle(fontSize: 25.sp),
                                ),
                              ),
                              Padding(
                                padding: EdgeInsets.only(left: 30.w),
                              ),
                              Row(
                                children: [
                                  Container(
                                    width: 360.w,
                                    margin: EdgeInsets.symmetric(vertical: 8.w),
                                    child: TextField(
                                      keyboardType: TextInputType.number,
                                      textAlign: TextAlign.justify,
                                      obscureText: false,
                                      maxLength: 6,
                                      maxLines: 1,
                                      onChanged: (value) {
                                        setState(() {
                                          captcha2 = value;
                                        });
                                      },
                                      style: TextStyle(fontSize: 25.sp, color: Config.colorText1),
                                      decoration: const InputDecoration(
                                        hintStyle: TextStyle(color: Config.colorText3),
                                        hintText: "请输入验证码",
                                        counterText: '',
                                        isDense: true,
                                        border: InputBorder.none,
                                        contentPadding: EdgeInsets.zero, //设置文本内容的Padding
                                      ),
                                    ),
                                  ),
                                  InkWell(
                                    onTap: () {
                                      if (!isGetCode2) {
                                        return;
                                      }
                                      if (newMobile.length < 11) {
                                        EasyLoading.showToast('请输入正确的手机号');
                                        return;
                                      }
                                      sendSms(newMobile);
                                      CountDownTimeUtil(60, 1, (int currentTime) {
                                        var _currentTime = currentTime;
                                        setState(() {
                                          if (_currentTime == 0) {
                                            codeTips2 = '获取验证码';
                                            isGetCode2 = true;
                                          } else {
                                            codeTips2 = '$_currentTime';
                                          }
                                        });
                                      });
                                      isGetCode2 = false;
                                    },
                                    child: Text(
                                      codeTips2,
                                      style: TextStyle(
                                        color: Config.colorMain,
                                        fontSize: 22.sp,
                                      ),
                                    ),
                                  ),
                                ],
                              ),
                            ],
                          ),
                        ],
                      ),
                    ),
                    Container(
                      width: 750.w,
                      height: 96.w,
                      padding: EdgeInsets.symmetric(vertical: 8.w, horizontal: 8.w),
                      margin: EdgeInsets.only(top: 45.w),
                      child: ElevatedButton(
                        clipBehavior: Clip.antiAlias,
                        onPressed: () {
                          if (newMobile.length < 11) {
                            EasyLoading.showToast('请输入正确的手机号');
                            return;
                          }
                          if (captcha2.length < 6) {
                            EasyLoading.showToast('请输入验证码');
                            return;
                          }
                          changeMobile(newMobile, captcha2);
                        },
                        style: ElevatedButton.styleFrom(shape: const StadiumBorder()),
                        child: const Text('确定'),
                      ),
                    ),
                  ],
                ),
              ),
            ),
          ],
        ),
      ),
    );
  }
}
